const fs = require('fs')
const path = require('path')
const express = require('express')
const cors = require('cors')
const server = express()
const qs = require('querystring')

server.use(cors())

let bookStr

server.get('/api/books', (req, res) => {
  fs.readFile(path.join(__dirname, 'data/book.json'), (err, data) => {
    const bookObj = JSON.parse(data.toString())
    bookStr = bookObj.data
    const bookList = bookStr.map(item => item.bookname)
    // console.log(bookObj)
    // res.send(data.toString())
    res.send(bookList)
  })
})

server.post('/api/books', (req, res) => { 
  // if (req.url === '/api/books') {
  //   const reqStr = req.url.split('?')[1]
  //   const reqObj = qs.parse(reqStr)
   
  //  console.log(reqStr)
  // data = {
  //   id,
  //   bookname,
  //   author,
  //   publisher
  //   }
  // }
  if ( req.url.startsWith('/api/books') && req.method === 'post' ){
    res.render(path.join(__dirname, 'data/book.json', '/api/books'));
    // let list=[]
    bookStr.push(urlObj.query);
    fs.writeFile(path.join(__dirname,'data/book.json'), JSON.stringify(bookStr), function(err){
        if(err){throw err;}
        console.log('ok');
    });
    //3.跳转到新闻列表页
        
}
  // bookStr.push(data)
  // fs.writeFile(path.join(__dirname,'data/book.json'), JSON.parse(data), err => {
  //   if (err) return console.log(err)
  //   else console.log('写入成功')
  // })
  // fs.appendFile(path.join(__dirname,'data/book.json'), JSON.parse(data), err => {
  //   if (err) return console.log(err)
  //   else console.log('写入成功')
  // })


})






server.all('*', (req, res) => {
  res.status(404)
  res.send('访问个勾八')
})

server.listen(3000, () => {
  console.log('启动')
})
